import SCMSaleApi from '../../../../../js/common/api/fi/salesvolumequery.api.js';
import doT from '../../../../../../public/vendor/template/doT.js'

let prePickDate = [];

(function (window, document, $) {
    let staffJson = {}, returnEntity = [], loginStuffCode, _ownOrgs = [], _stuffInfo = [];
    const _addSaleTableHtml = '<tr id="row-placeholder"><td colspan="4" style="text-align: center" >暂无销售数据</td></tr>';
    const _addGroupTableHtml = '<tr id="group-placeholder"><td colspan="5" style="text-align: center" >暂无销售数据</td></tr>';
    const _addGroupTableSummaryHtml = '<tr id="groupSummary-placeholder"><td colspan="5" style="text-align: center" >暂无销售数据</td></tr>';

    $(function () {
        initPicker()
        initCommand();
        initMeData();
        initCurrentMonth()

        $(document).on('mousedown', '.select2-container--open', function (e) {
            e.target.style.fontSize = '15px'
        });
        $(document).on('focus', '.select2-container--open', function (e) {
            e.target.style.fontSize = '15px'
        });
        $('body').attr('data-weui-theme', 'light'); // 强制光明模式
    });

    const initCommand = async function () {
        // TODO:切换时间
        $(document).on('click', '.dtPicker-container a', function () {
            $(this).addClass('dtPicker-hightLight-Cotainer')
            $(this).removeClass('dtPicker-normal-Cotainer')
            $(this).siblings().removeClass('dtPicker-hightLight-Cotainer')
            $(this).siblings().addClass('dtPicker-normal-Cotainer')
        })

        // TODO:重置时间选择
        $(document).on('click', '.reset-picker', function () {
            $('#startDate').text('开始时间')
            $('#endDate').text('结束时间')
            $('#startDate').attr('data-value', '')
            $('#endDate').attr('data-value', '')
            initCurrentMonth()
        });

        //返回首页
        $('.returnMain').on('click', function () {
            location.href = '../../../main.html'
        });

        //刷新数据
        $('.buttonRefresh').on('click', function () {
            let synchData = {
                "startDate": moment().startOf('month').format('YYYY-MM-DD'),
                "endDate": moment().format('YYYY-MM-DD')
            }
            // $.showLoading(`请求成功！若数据刷新后仍存在异常，请联系销售内勤核对业务单据数据。`);
            SCMSaleApi.postSellerSaleSynch(synchData).then(res => {
                if (res.isSucceed) {
                    $("#forbiddenModal").show();
                    setTimeout(() => { $('#forbiddenModal').hide() }, 3000)
                    restTable();
                }
            });
        });

        $(document).on('click', '.weui-navbar__item', function () {
            let tabValue = $(this)[0].id;
            if (!Utils.IsNotNull(tabValue)) { //个人
                $('#saleTab').attr("style", "display:block");
                $('#groupSaleTab').attr("style", "display:none");
            } else {
                $('#saleTab').attr("style", "display:none");
                $('#groupSaleTab').attr("style", "display:block");
                $('#saleGroup-table-id thead tr th').eq(1).text('');
                $('#saleGroup-table-id thead tr th').eq(1).text($(this)[0].innerText);
                $('#saleGroupSummary-table-id thead tr th').eq(1).text('');
                $('#saleGroupSummary-table-id thead tr th').eq(1).text($(this)[0].innerText);
            }
        });

        // _stuffInfo = await SCMSaleApi.getUserInfo();
        _stuffInfo = JSON.parse(Utils.GetSessionStorage("SNLoginUserInfo")) || {}
        _ownOrgs = await SCMSaleApi.postUserOrgsList();
        SCMSaleApi.getOrgsListType().then(res => {
            let sale = res.filter(s => s.typeValue == true);
            let obj = _ownOrgs.filter(item => sale.some(item2 => item2.id == item.oId));
            let ownAccount = obj.find(s => s.oId == _stuffInfo.curOrgId);
            $('#saleOrgs').select2({
                placeholder: '请选择销售组织...', //默认文字提示
                language: "zh-CN",//汉化
                //allowClear: true,//允许清空
                data: obj.map(item => {
                    return {
                        id: item.oId,
                        name: item.oName,
                        text: `${item.oName}`
                    }
                }),
            });
            if (Utils.IsNotNull(ownAccount)) {
                $('#saleOrgs').val(ownAccount.oId).trigger('change');
            }
        });
        $('#saleOrgs').on('select2:select', function () {
            restTable();
        });
    }

    // 初始化picker
    const initPicker = () => {
        // 获得昨天日期
        initCurrentMonth()

        let index = 0;
        $('.pick-time').on('click', function (e) {
            e.stopPropagation();
            $('.pick-time').picker('open')
            $("#startDate").text(prePickDate[0] || '开始时间')
            $("#endDate").text(prePickDate[1] || '结束时间')
            $("#startDate").attr("data-value", prePickDate[0])
            $("#endDate").attr("data-value", prePickDate[1])
        })
        let betweenChar = -
            $('.pick-time').datetimePicker(
                {
                    toolbarTemplate: $('#date-pick-template').html(),
                    // max:formatDate,
                    toolbarCloseText: "确定",
                    defaultValue: prePickDate,
                    yearSplit: '年',
                    monthSplit: '月',
                    dateSplit: '日',
                    times: function () {
                        return [];
                    },
                    //选择值变化时的操作
                    onChange: function (picker) {
                        if (index == 0) return index++;
                        let value = picker.value[0] + '-' + picker.value[1] + '-' + picker.value[2]
                        $('.dtPicker-hightLight-Cotainer .chooseDate').text(value);
                        let id = $('.dtPicker-hightLight-Cotainer .chooseDate').attr("id")
                        $(`#${id}`).attr("data-value", value);
                    },
                    //确定选择时的操作
                    onClose: function () {
                        let _start = $("#startDate").attr("data-value");
                        let _end = $("#endDate").attr("data-value");
                        if (_start || _end) {
                            betweenChar = _start && _end ? '~' : ''
                            $('.pick-time-text').text(`${_start || ''} ${betweenChar} ${_end || ''}`);
                            if (_start && _end) {
                                prePickDate = [_start, _end]
                            } else if (!_start) {
                                prePickDate = [_end, _end]
                            } else {
                                prePickDate = [_start, _start]
                            }
                        } else {
                            $('.pick-time-text').text('请选择业务日期');
                            initCurrentMonth()
                        }
                        restTable();
                    }
                }
            );
    }

    // 初始化数据
    const initMeData = async () => {
        //获取员工信息
        staffJson = {};
        staffJson = await SCMSaleApi.getStuffInfo();
        let sellerCode = {
            "code": staffJson.numCode
        }
        loginStuffCode = staffJson.numCode
        //获取销售组内销售员列表
        SCMSaleApi.getSellerSaleList(sellerCode).then(res => {
            let _template = doT.template($('#type-sale-template').text());
            $('.weui-navbar').append(_template({ list: res }));
            // TODO:切换Tab
            weui.tab('#area-tab', {
                defaultIndex: 0,
                onChange: function (index) {
                    returnEntity = []
                    if (index == 0) return;
                    let chooseEntity = res.find(d => d.type == (parseInt(this.id))).entity
                    chooseEntity.forEach(item => {
                        if (item.empCode !== loginStuffCode) {
                            returnEntity.push({ 'groupName': item.groupName, 'code': item.empCode })
                        }
                    })
                    _departmentSellerSale(returnEntity);
                }
            });
            querySelfSale();
        });
    }

    //获取个人销量
    const querySelfSale = () => {
        let selfSale = {
            "begDate": prePickDate[0],
            "endDate": prePickDate[1],
            "code": staffJson.numCode
        }
        SCMSaleApi.getSelfSaleList(selfSale).then(res => {
            let _qty = [];
            if (res.length == 0) {
                return $('#self-tbody').empty().append(_addSaleTableHtml);
            }
            res = sortFunction(res)
            let _template = doT.template($('#self-sale-template').text());
            $('#row-placeholder').remove();
            $('#self-tbody').empty();
            $('#self-tbody').append(_template({ list: res }));
            $.each(res, function (i, v) {
                _qty.push(v.qty);
            });
            let totalQty = _qty.reduce((pre, cur) => {//对象中属性的总和
                return pre + cur;
            }, 0);
            $('.qty').text(totalQty.toFixed(2));
        });
    }

    //获取销量组销量
    const _departmentSellerSale = (chooseEntity) => {

        let saleGroup = {
            "begDate": prePickDate[0],
            "endDate": prePickDate[1],
            "orgName": $('#saleOrgs').select2('data')[0].name,
            "empentily": chooseEntity
        }
        SCMSaleApi.postSellerSaleGroup(saleGroup).then(res => {
            _departmentSellerSaleSummary(res)
            if (res.length == 0) {
                return $('#group-tbody').empty().append(_addGroupTableHtml);
            }
            res = sortFunction(res)
            let _qty = [];
            $.each(res, function (i, v) {
                _qty.push(v.qty);
            });
            //let totalQty = _qty.reduce((pre, cur) => {//对象中属性的总和
            //    return pre + cur;
            //}, 0);
            let totalQty = eval(_qty.join('+'));
            let _template = doT.template($('#group-sale-template').text());
            $('#group-placeholder').remove();
            $('#group-tbody').empty();
            $('#group-tbody').append(_template({ list: res }));
            $('.qtyAmount').text(totalQty.toFixed(2));
        });
    }

    // 获取销售组销量合计
    const _departmentSellerSaleSummary = (res) => {
        if (res.length == 0) {
            return $('#groupSummary-tbody').empty().append(_addGroupTableSummaryHtml);
        }
        let _template = doT.template($('#groupSummary-sale-template').text());
        let summaryData = handleSummary(res, 'groupName', 'qty')
        $('#groupSummary-placeholder').remove();
        $('#groupSummary-tbody').empty();
        $('#groupSummary-tbody').append(_template({ list: summaryData.summaryList }))
        $('.qtySummaryAmount').text(summaryData.summaryTotal.toFixed(2))
    };

    // 排序
    const sortFunction = (array) => {
        array = array.sort(function (a, b) {
            return b.qty - a.qty
        })
        return array
    }


    // 数组中对象相同键去重求和
    const handleSummary = function (resData) {
        let temp = {};
        let totalQty = 0
        for (var i in resData) {
            let key = resData[i].groupName;
            if (temp[key]) {
                temp[key].groupName = resData[i].groupName;
                temp[key].qty += resData[i].qty;
            } else {
                temp[key] = {};
                temp[key].groupName = resData[i].groupName;
                temp[key].qty = resData[i].qty;
            }
            totalQty += resData[i].qty
        }
        let newArry = [];
        for (var k in temp) {
            newArry.push(temp[k]);
        }

        return { "summaryList": sortFunction(newArry), "summaryTotal": totalQty };
    }

    //清空表格数据后重新加载
    const restTable = () => {
        $('.qty').text('');
        $('.qtyAmount').text('');
        $('.qtySummaryAmount').text('');
        querySelfSale();
        _departmentSellerSale(returnEntity);
    }

    // 获取本月日期
    const initCurrentMonth = () => {
        let monthStartDate = moment().startOf('month').format('YYYY-MM-DD');
        let todayDate = moment().format('YYYY-MM-DD')
        prePickDate = [monthStartDate, todayDate]
        let showDate = prePickDate[0] + '~' + prePickDate[1]
        $('.pick-time-text').text(showDate)
    }

})(window, document, jQuery);
